<template>
  <div class="dataset-manager">
    <div class="dataset-header">
      <h3>数据集管理</h3>
      <el-button 
        type="primary" 
        size="small" 
        :icon="Plus"
        @click="createNewConversation"
      >
        新增对话
      </el-button>
    </div>

    <div class="dataset-info" v-if="datasetStore.currentDataset.name">
      <el-card shadow="never" class="info-card">
        <div class="dataset-name">
          <el-icon><component :is="Document" /></el-icon>
          <span 
            v-if="!editingDatasetName"
            @dblclick="startEditDatasetName"
            class="dataset-name-text"
            title="双击编辑数据集名称"
          >
            {{ datasetStore.currentDataset.name }}
          </span>
          <div v-else class="dataset-name-editor">
            <el-input
              v-model="datasetNameInput"
              size="small"
              @blur="saveDatasetName"
              @keyup.enter="saveDatasetName"
              @keyup.esc="cancelEditDatasetName"
              ref="datasetNameInputRef"
              placeholder="输入数据集名称"
            />
          </div>
        </div>
        <div class="dataset-stats" v-if="datasetStore.datasetStats">
          <div class="stat-item">
            <span class="label">对话数:</span>
            <span class="value">{{ datasetStore.datasetStats.totalConversations }}</span>
          </div>
          <div class="stat-item">
            <span class="label">消息数:</span>
            <span class="value">{{ datasetStore.datasetStats.totalMessages }}</span>
          </div>
        </div>
      </el-card>
    </div>

    <div class="conversation-list">
      <h4>对话列表</h4>
      <div class="conversation-items">
        <div 
          v-for="(conversation, index) in datasetStore.currentDataset.data"
          :key="index"
          class="conversation-item"
          :class="{ active: conversationStore.currentConversationIndex === index }"
          @click="selectConversation(index)"
        >
          <div class="conversation-preview">
            <div class="conversation-title">
              <span 
                v-if="editingConversationIndex !== index"
                @dblclick="startEditConversationName(index)"
                class="conversation-name-text"
                title="双击编辑对话名称"
              >
                {{ conversation.name || `对话 ${index + 1}` }}
              </span>
              <div v-else class="conversation-name-editor" @click.stop>
                <el-input
                  v-model="conversationNameInput"
                  size="small"
                  @blur="saveConversationName"
                  @keyup.enter="saveConversationName"
                  @keyup.esc="cancelEditConversationName"
                  ref="conversationNameInputRef"
                  placeholder="输入对话名称"
                />
              </div>
              <div class="conversation-tags">
                <el-tag v-if="conversation.system" size="small" type="info">系统</el-tag>
                <el-tag v-if="conversation.tools" size="small" type="warning">工具</el-tag>
              </div>
            </div>
            <div class="conversation-summary">
              {{ getConversationSummary(conversation) }}
            </div>
          </div>
          
          <div class="conversation-actions">
            <el-button-group size="small">
              <el-button 
                :icon="Edit" 
                @click.stop="editConversation(index)"
                circle
                size="small"
                title="编辑对话名称"
              />
              <el-button 
                :icon="Delete" 
                type="danger"
                @click.stop="deleteConversation(index)"
                circle
                size="small"
              />
            </el-button-group>
          </div>
        </div>
      </div>
    </div>

    <!-- 删除对话确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="删除确认"
      width="400px"
      :close-on-click-modal="false"
      @close="handleDeleteDialogClose"
    >
      <div class="delete-dialog-content">
        <el-icon class="warning-icon" color="#E6A23C" size="24px">
          <WarningFilled />
        </el-icon>
        <div class="delete-message">
          确定要删除这个对话吗？此操作不可恢复。
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDeleteAction('cancel')" size="default">
            取消
          </el-button>
          <el-button @click="handleDeleteAction('confirm')" type="danger" size="default">
            删除
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, nextTick } from 'vue'
import { useDatasetStore } from '../../stores/dataset.js'
import { useConversationStore } from '../../stores/conversation.js'
import { ElMessage } from 'element-plus'
import { Document, Edit, Delete, Plus, WarningFilled } from '@element-plus/icons-vue'

const datasetStore = useDatasetStore()
const conversationStore = useConversationStore()

// 删除对话框相关数据
const deleteDialogVisible = ref(false)
const deleteTargetIndex = ref(-1)

// 编辑数据集名称相关数据
const editingDatasetName = ref(false)
const datasetNameInput = ref('')
const datasetNameInputRef = ref()

// 编辑对话名称相关数据
const editingConversationIndex = ref(-1)
const conversationNameInput = ref('')
const conversationNameInputRef = ref()

// 选择对话
const selectConversation = (index) => {
  const result = conversationStore.selectConversation(index)
  
  // 如果自动保存成功，显示提示
  if (result && result.autoSaved) {
    ElMessage.success('已自动保存编辑中的消息')
  }
}

// 创建新对话
const createNewConversation = () => {
  datasetStore.addConversation()
  // 选中新创建的对话
  const newIndex = datasetStore.currentDataset.data.length - 1
  conversationStore.selectConversation(newIndex)
}

// 编辑对话名称
const editConversation = (index) => {
  startEditConversationName(index)
}

// 删除对话
const deleteConversation = (index) => {
  deleteTargetIndex.value = index
  deleteDialogVisible.value = true
}

// 处理删除对话框的操作
const handleDeleteAction = (action) => {
  deleteDialogVisible.value = false
  
  if (action === 'cancel') {
    return // 取消操作
  }
  
  if (action === 'confirm') {
    const index = deleteTargetIndex.value
    datasetStore.removeConversation(index)
    
    // 如果删除的是当前选中的对话，重新选择
    if (conversationStore.currentConversationIndex === index) {
      const newIndex = Math.min(index, datasetStore.currentDataset.data.length - 1)
      if (newIndex >= 0) {
        conversationStore.selectConversation(newIndex)
      } else {
        conversationStore.selectConversation(-1)
      }
    }
    
    ElMessage.success('对话已删除')
  }
}

// 处理对话框关闭（点击X或ESC）
const handleDeleteDialogClose = () => {
  deleteDialogVisible.value = false
}

// 获取对话摘要
const getConversationSummary = (conversation) => {
  if (!conversation.conversations || conversation.conversations.length === 0) {
    return '空对话'
  }
  
  const firstHuman = conversation.conversations.find(msg => msg.from === 'human')
  if (firstHuman && firstHuman.value) {
    return firstHuman.value.length > 30 
      ? firstHuman.value.substring(0, 30) + '...'
      : firstHuman.value
  }
  
  return `${conversation.conversations.length} 条消息`
}

// 数据集名称编辑相关方法
const startEditDatasetName = () => {
  editingDatasetName.value = true
  datasetNameInput.value = datasetStore.currentDataset.name
  nextTick(() => {
    datasetNameInputRef.value?.focus()
  })
}

const saveDatasetName = () => {
  if (datasetNameInput.value.trim()) {
    datasetStore.updateDatasetName(datasetNameInput.value.trim())
    ElMessage.success('数据集名称已更新')
  }
  editingDatasetName.value = false
}

const cancelEditDatasetName = () => {
  editingDatasetName.value = false
  datasetNameInput.value = ''
}

// 对话名称编辑相关方法
const startEditConversationName = (index) => {
  editingConversationIndex.value = index
  const conversation = datasetStore.currentDataset.data[index]
  conversationNameInput.value = conversation.name || `对话 ${index + 1}`
  nextTick(() => {
    conversationNameInputRef.value?.focus()
  })
}

const saveConversationName = () => {
  if (conversationNameInput.value.trim()) {
    datasetStore.updateConversationName(editingConversationIndex.value, conversationNameInput.value.trim())
    ElMessage.success('对话名称已更新')
  }
  editingConversationIndex.value = -1
}

const cancelEditConversationName = () => {
  editingConversationIndex.value = -1
  conversationNameInput.value = ''
}
</script>

<style scoped>
.dataset-manager {
  height: 100%;
  padding: 16px;
  display: flex;
  flex-direction: column;
}

.dataset-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.dataset-header h3 {
  margin: 0;
  color: #303133;
}

.dataset-info {
  margin-bottom: 16px;
}

.info-card {
  border: 1px solid #e4e7ed;
}

.dataset-name {
  display: flex;
  align-items: center;
  font-weight: 500;
  margin-bottom: 8px;
}

.dataset-name .el-icon {
  margin-right: 8px;
  color: #909399;
}

.dataset-name-text {
  cursor: pointer;
  padding: 2px 4px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.dataset-name-text:hover {
  background-color: #f5f7fa;
}

.dataset-name-editor {
  flex: 1;
}

.dataset-stats {
  display: flex;
  gap: 16px;
  font-size: 12px;
}

.stat-item {
  display: flex;
  align-items: center;
}

.stat-item .label {
  color: #909399;
  margin-right: 4px;
}

.stat-item .value {
  color: #303133;
  font-weight: 500;
}

.conversation-list {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.conversation-list h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 14px;
}

.conversation-items {
  flex: 1;
  overflow-y: auto;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.conversation-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border-bottom: 1px solid #e4e7ed;
  cursor: pointer;
  transition: background-color 0.3s;
}

.conversation-item:last-child {
  border-bottom: none;
}

.conversation-item:hover {
  background-color: #f5f7fa;
}

.conversation-item.active {
  background-color: #e6f7ff;
  border-color: #409eff;
}

.conversation-preview {
  flex: 1;
  min-width: 0;
}

.conversation-title {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 500;
  font-size: 13px;
  margin-bottom: 4px;
}

.conversation-name-text {
  cursor: pointer;
  padding: 2px 4px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.conversation-name-text:hover {
  background-color: #f5f7fa;
}

.conversation-name-editor {
  flex: 1;
  margin-right: 8px;
}

.conversation-tags {
  display: flex;
  gap: 4px;
}

.conversation-summary {
  font-size: 12px;
  color: #909399;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.conversation-actions {
  flex-shrink: 0;
  margin-left: 8px;
}

.delete-dialog-content {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 16px 0;
}

.warning-icon {
  flex-shrink: 0;
  margin-top: 2px;
}

.delete-message {
  flex: 1;
  font-size: 14px;
  line-height: 1.5;
  color: #606266;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}
</style> 